<template>
  <div class="admin-page">
    <el-card class="admin-card">
      <template #header>
        <page-header title="系统设置" />
      </template>

      <div class="admin-page-content">
        <!-- 系统维护设置 -->
        <el-card class="settings-section" shadow="never">
          <template #header>
            <div class="card-header">
              <span class="card-title">系统维护设置</span>
            </div>
          </template>
          
          <el-form 
            :model="maintenanceForm"
            label-width="100px"
            v-loading="maintenanceLoading"
          >
            <div class="maintenance-content">
              <div class="maintenance-form">
                <el-form-item label="维护状态">
                  <el-switch
                    v-model="maintenanceForm.enabled"
                    :active-value="true"
                    :inactive-value="false"
                    active-text="开启"
                    inactive-text="关闭"
                  />
                </el-form-item>
                
                <el-form-item label="维护提示" class="message-item">
                  <el-input
                    v-model="maintenanceForm.message"
                    type="textarea"
                    :rows="1"
                    placeholder="请输入系统维护时显示的提示文本"
                  />
                </el-form-item>

                <el-form-item class="action-item">
                  <el-button 
                    type="primary" 
                    @click="handleMaintenanceSave"
                    :loading="maintenanceLoading"
                    size="small"
                  >
                    保存设置
                  </el-button>
                </el-form-item>
              </div>
            </div>
          </el-form>
        </el-card>

        <!-- 基础设置 -->
        <el-card class="settings-section" shadow="never">
          <template #header>
            <div class="card-header">
              <span class="card-title">基础设置</span>
            </div>
          </template>
          
          <div class="settings-grid">
            <!-- 系统Logo -->
            <el-card class="settings-card" shadow="never">
              <template #header>
                <div class="card-header">
                  <span class="card-title">系统Logo</span>
                  <el-button 
                    type="primary" 
                    @click="handleBasicSave"
                    :loading="basicLoading"
                    size="small"
                  >
                    保存设置
                  </el-button>
                </div>
              </template>
              
              <el-form 
                :model="basicForm"
                label-width="0"
              >
                <div class="upload-item">
                  <div class="upload-wrapper">
                    <div class="upload-label">Logo</div>
                    <div class="upload-content">
                      <div class="upload-preview" v-if="basicForm.logo">
                        <el-image 
                          :src="getImageUrl(basicForm.logo)"
                          class="preview-image"
                          fit="contain"
                        />
                        <div class="preview-actions">
                          <el-button type="danger" link @click="handleRemoveFile('logo')">
                            删除
                          </el-button>
                        </div>
                      </div>
                      <el-upload
                        v-else
                        class="upload-area"
                        action="#"
                        :http-request="file => handleUpload(file, 'logo')"
                        :show-file-list="false"
                        accept="image/png"
                      >
                        <div class="upload-placeholder">
                          <el-icon class="upload-icon"><Plus /></el-icon>
                          <div class="upload-text">点击上传</div>
                          <div class="upload-tip">(推荐尺寸: 120x40px)</div>
                        </div>
                      </el-upload>
                    </div>
                  </div>

                  <div class="upload-wrapper">
                    <div class="upload-label">浏览器favicon.ico</div>
                    <div class="upload-content">
                      <div class="upload-preview" v-if="basicForm.favicon">
                        <el-image 
                          :src="getImageUrl(basicForm.favicon)"
                          class="preview-image"
                          fit="contain"
                        />
                        <div class="preview-actions">
                          <el-button type="danger" link @click="handleRemoveFile('favicon')">
                            删除
                          </el-button>
                        </div>
                      </div>
                      <el-upload
                        v-else
                        class="upload-area"
                        action="#"
                        :http-request="file => handleUpload(file, 'favicon')"
                        :show-file-list="false"
                        accept="image/x-icon"
                      >
                        <div class="upload-placeholder">
                          <el-icon class="upload-icon"><Plus /></el-icon>
                          <div class="upload-text">点击上传</div>
                          <div class="upload-tip">(推荐尺寸: 32x32px)</div>
                        </div>
                      </el-upload>
                    </div>
                  </div>
                </div>
              </el-form>
            </el-card>

            <!-- 系统名称和页面配置 -->
            <el-card class="settings-card" shadow="never">
              <template #header>
                <div class="card-header">
                  <span class="card-title">系统文字设置</span>
                  <el-button 
                    type="primary" 
                    @click="handleBasicSave"
                    :loading="basicLoading"
                    size="small"
                  >
                    保存设置
                  </el-button>
                </div>
              </template>
              
              <el-form 
                :model="basicForm"
                label-width="80px"
              >
                <el-form-item label="前台名称">
                  <el-input 
                    v-model="basicForm.frontendName" 
                    maxlength="8"
                    show-word-limit
                    placeholder="8个中文字符以内"
                  />
                </el-form-item>

                <el-form-item label="后台名称">
                  <el-input 
                    v-model="basicForm.backendName" 
                    maxlength="8"
                    show-word-limit
                    placeholder="8个中文字符以内"
                  />
                </el-form-item>

                <el-form-item label="欢迎语">
                  <el-input
                    v-model="basicForm.welcomeText"
                    type="textarea"
                    :rows="1"
                    placeholder="请输入登录页欢迎语"
                  />
                </el-form-item>

                <el-form-item label="页面页尾">
                  <el-input
                    v-model="basicForm.footer"
                    type="textarea"
                    :rows="2"
                    placeholder="前台页面页尾内容（支持简单HTML格式）"
                  />
                </el-form-item>
              </el-form>
            </el-card>

            <!-- 登录页设置 -->
            <el-card class="settings-card" shadow="never">
              <template #header>
                <div class="card-header">
                  <span class="card-title">登录页设置</span>
                  <el-button 
                    type="primary" 
                    @click="handleBasicSave"
                    :loading="basicLoading"
                    size="small"
                  >
                    保存设置
                  </el-button>
                </div>
              </template>
              
              <el-form 
                :model="basicForm"
                label-width="0"
              >
                <div class="upload-item">
                  <div class="upload-wrapper">
                    <div class="upload-label">背景图</div>
                    <div class="upload-content">
                      <div class="upload-preview" v-if="basicForm.loginBackground">
                        <el-image 
                          :src="getImageUrl(basicForm.loginBackground)"
                          class="preview-image preview-bg"
                          fit="cover"
                        />
                        <div class="preview-actions">
                          <el-button type="danger" link @click="handleRemoveFile('loginBackground')">
                            删除
                          </el-button>
                        </div>
                      </div>
                      <el-upload
                        v-else
                        class="upload-area"
                        action="#"
                        :http-request="file => handleUpload(file, 'loginBackground')"
                        :show-file-list="false"
                        accept="image/jpeg"
                      >
                        <div class="upload-placeholder">
                          <el-icon class="upload-icon"><Plus /></el-icon>
                          <div class="upload-text">点击上传</div>
                          <div class="upload-tip">(推荐尺寸: 1920x1080px)</div>
                        </div>
                      </el-upload>
                    </div>
                  </div>

                  <div class="upload-wrapper">
                    <div class="upload-label">登录页标识</div>
                    <div class="upload-content">
                      <div class="upload-preview" v-if="basicForm.loginLogo">
                        <el-image 
                          :src="getImageUrl(basicForm.loginLogo)"
                          class="preview-image"
                          fit="contain"
                        />
                        <div class="preview-actions">
                          <el-button type="danger" link @click="handleRemoveFile('loginLogo')">
                            删除
                          </el-button>
                        </div>
                      </div>
                      <el-upload
                        v-else
                        class="upload-area"
                        action="#"
                        :http-request="file => handleUpload(file, 'loginLogo')"
                        :show-file-list="false"
                        accept="image/png"
                      >
                        <div class="upload-placeholder">
                          <el-icon class="upload-icon"><Plus /></el-icon>
                          <div class="upload-text">点击上传</div>
                          <div class="upload-tip">(推荐尺寸: 200x60px)</div>
                        </div>
                      </el-upload>
                    </div>
                  </div>
                </div>
              </el-form>
            </el-card>
          </div>
        </el-card>

        <!-- 存储管理 -->
        <el-card class="settings-section" shadow="never">
          <template #header>
            <div class="card-header">
              <span class="card-title">存储配置</span>
              <div class="header-actions">
                <el-button
                  type="primary"
                  size="small"
                  :loading="testStorageLoading"
                  @click="handleTestStorage"
                >
                  测试连接
                </el-button>
                <el-button
                  type="primary"
                  size="small"
                  :loading="storageLoading"
                  @click="handleSaveStorage"
                >
                  保存设置
                </el-button>
              </div>
            </div>
          </template>

          <el-card shadow="never" class="inner-card">
            <el-form
              ref="storageFormRef"
              :model="storageForm"
              label-width="120px"
              class="storage-form"
            >
              <!-- 第一行：存储方式和服务商 -->
              <div class="storage-row">
                <el-form-item label="存储方式">
                  <el-select
                    v-model="storageForm.type"
                    style="width: 150px"
                    @change="handleStorageTypeChange"
                  >
                    <el-option label="本地存储" value="local" />
                    <el-option label="对象存储" value="oss" />
                  </el-select>
                </el-form-item>

                <el-form-item label="服务商" v-if="storageForm.type === 'oss'">
                  <el-select
                    v-model="storageForm.provider"
                    style="width: 150px"
                    @change="handleStorageProviderChange"
                  >
                    <el-option label="阿里云" value="aliyun" />
                    <el-option label="腾讯云" value="tencent" />
                    <el-option label="七牛云" value="qiniu" />
                    <el-option label="华为云" value="huawei" />
                  </el-select>
                </el-form-item>
              </div>

              <!-- 第二行：其他配置项 -->
              <div class="storage-row" v-if="storageForm.type === 'oss'">
                <el-form-item label="AccessKey">
                  <el-input
                    v-model="storageForm.accessKey"
                    style="width: 150px"
                    placeholder="请输入AccessKey"
                  />
                </el-form-item>

                <el-form-item label="AccessSecret" style="margin-left: 0px">
                  <el-input
                    v-model="storageForm.secretKey"
                    style="width: 150px"
                    type="password"
                    placeholder="请输入AccessSecret"
                    show-password
                  />
                </el-form-item>

                <el-form-item label="区域" style="margin-left: -30px">
                  <el-input
                    v-model="storageForm.region"
                    style="width: 115px"
                    placeholder="请输入区域"
                  />
                </el-form-item>

                <el-form-item label="Bucket" style="margin-left: -30px">
                  <el-input
                    v-model="storageForm.bucket"
                    style="width: 115px"
                    placeholder="请输入Bucket"
                  />
                </el-form-item>

                <el-form-item label="域名" style="margin-left: -20px">
                  <div class="domain-wrapper">
                    <el-select v-model="storageForm.protocol" style="width: 100px">
                      <el-option label="HTTP" value="http" />
                      <el-option label="HTTPS" value="https" />
                    </el-select>
                    <el-input
                      v-model="storageForm.domain"
                      style="width: 230px"
                      placeholder="预分配或CDN域名"
                    />
                  </div>
                </el-form-item>
              </div>
            </el-form>
          </el-card>
        </el-card>

        <!-- 邮件配置 -->
        <el-card class="settings-section" shadow="never">
          <template #header>
            <div class="card-header">
              <span class="card-title">邮件配置</span>
              <div class="header-actions">
                <el-button 
                  type="primary" 
                  @click="handleTestMail"
                  :loading="testMailLoading"
                  size="small"
                >
                  发送测试
                </el-button>
                <el-button 
                  type="primary" 
                  @click="handleMailSave"
                  :loading="mailLoading"
                  size="small"
                >
                  保存设置
                </el-button>
              </div>
            </div>
          </template>
          
          <el-form 
            :model="mailForm"
            label-width="100px"
            v-loading="mailLoading"
          >
            <div class="mail-content">
              <div class="mail-form">
                <el-form-item label="SMTP服务器">
                  <el-input 
                    v-model="mailForm.mailerHost" 
                    placeholder="smtp.xxx.com"
                  />
                </el-form-item>

                <el-form-item label="SMTP端口">
                  <el-input 
                    v-model="mailForm.mailerPort" 
                    placeholder="465"
                    style="width: 120px"
                  />
                </el-form-item>

                <el-form-item label="邮箱账号">
                  <el-input 
                    v-model="mailForm.mailerUser" 
                    placeholder="xxx@xxx.com"
                  />
                </el-form-item>

                <el-form-item label="邮箱密码">
                  <el-input 
                    v-model="mailForm.mailerPass" 
                    type="password"
                    placeholder="请输入密码或授权码"
                    show-password
                  />
                </el-form-item>

                <el-form-item label="发件人">
                  <el-input 
                    v-model="mailForm.mailerFrom" 
                    placeholder="系统名称 <xxx@xxx.com>"
                  />
                </el-form-item>
              </div>
            </div>
          </el-form>
        </el-card>

        <!-- 短信配置 -->
        <el-card class="settings-section" shadow="never">
          <template #header>
            <div class="card-header">
              <span class="card-title">短信配置</span>
              <div class="header-actions">
                <el-button type="primary" @click="handleTestSms">测试发送</el-button>
                <el-button type="primary" @click="handleSaveSmsConfig">保存设置</el-button>
              </div>
            </div>
          </template>
          <div class="sms-content">
            <el-form ref="smsFormRef" :model="smsForm" class="sms-form">
              <!-- 服务商选择单独一行 -->
              <div class="provider-row">
                <el-form-item label="服务商">
                  <el-select v-model="smsForm.provider" placeholder="选择服务商">
                    <el-option label="阿里云" value="aliyun" />
                    <el-option label="腾讯云" value="tencent" />
                    <el-option label="华为云" value="huawei" />
                    <el-option label="七牛云" value="qiniu" />
                  </el-select>
                </el-form-item>
              </div>

              <!-- 配置项容器 -->
              <div class="config-row">
                <!-- 阿里云配置项 -->
                <template v-if="smsForm.provider === 'aliyun'">
                  <el-form-item label="AccessKey ID">
                    <el-input v-model="smsForm.accessKeyId" show-password placeholder="请输入AccessKey ID" />
                  </el-form-item>
                  <el-form-item label="AccessKey Secret">
                    <el-input v-model="smsForm.accessKeySecret" show-password placeholder="请输入AccessKey Secret" />
                  </el-form-item>
                  <el-form-item label="签名名称">
                    <el-input v-model="smsForm.signName" placeholder="请输入签名名称" />
                  </el-form-item>
                  <el-form-item label="模板CODE">
                    <el-input v-model="smsForm.templateCode" placeholder="请输入模板CODE" />
                  </el-form-item>
                </template>

                <!-- 腾讯云配置项 -->
                <template v-else-if="smsForm.provider === 'tencent'">
                  <el-form-item label="SecretId">
                    <el-input v-model="smsForm.secretId" show-password placeholder="请输入SecretId" />
                  </el-form-item>
                  <el-form-item label="SecretKey">
                    <el-input v-model="smsForm.secretKey" show-password placeholder="请输入SecretKey" />
                  </el-form-item>
                  <el-form-item label="应用AppID">
                    <el-input v-model="smsForm.appId" placeholder="请输入应用AppID" />
                  </el-form-item>
                  <el-form-item label="签名内容">
                    <el-input v-model="smsForm.signContent" placeholder="请输入签名内容" />
                  </el-form-item>
                  <el-form-item label="模板ID">
                    <el-input v-model="smsForm.templateId" placeholder="请输入模板ID" />
                  </el-form-item>
                </template>

                <!-- 华为云配置项 -->
                <template v-else-if="smsForm.provider === 'huawei'">
                  <el-form-item label="APP_Key">
                    <el-input v-model="smsForm.appKey" show-password placeholder="请输入APP_Key" />
                  </el-form-item>
                  <el-form-item label="APP_Secret">
                    <el-input v-model="smsForm.appSecret" show-password placeholder="请输入APP_Secret" />
                  </el-form-item>
                  <el-form-item label="通道号">
                    <el-input v-model="smsForm.channelNumber" placeholder="请输入通道号" />
                  </el-form-item>
                  <el-form-item label="签名">
                    <el-input v-model="smsForm.signature" placeholder="请输入签名" />
                  </el-form-item>
                  <el-form-item label="模板ID">
                    <el-input v-model="smsForm.templateId" placeholder="请输入模板ID" />
                  </el-form-item>
                </template>

                <!-- 七牛云配置项 -->
                <template v-else-if="smsForm.provider === 'qiniu'">
                  <el-form-item label="AccessKey">
                    <el-input v-model="smsForm.accessKey" show-password placeholder="请输入AccessKey" />
                  </el-form-item>
                  <el-form-item label="SecretKey">
                    <el-input v-model="smsForm.secretKey" show-password placeholder="请输入SecretKey" />
                  </el-form-item>
                  <el-form-item label="签名">
                    <el-input v-model="smsForm.signature" placeholder="请输入签名" />
                  </el-form-item>
                  <el-form-item label="模板ID">
                    <el-input v-model="smsForm.templateId" placeholder="请输入模板ID" />
                  </el-form-item>
                </template>
              </div>
            </el-form>
          </div>
        </el-card>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getMaintenanceConfig, updateMaintenanceConfig } from '@/api/system'
import { useSystemStore } from '@/stores/system'
import PageHeader from '@/components/PageHeader.vue'
import { getMailConfig, updateMailConfig, testMailSend } from '@/api/systemApi'
import * as systemApi from '@/api/systemApi'

const systemStore = useSystemStore()

const loading = ref(false)
const maintenanceForm = ref({
  enabled: false,
  message: ''
})

const basicForm = ref({
  frontendName: '',
  backendName: '',
  logo: '',
  favicon: '',
  loginBackground: '',
  loginLogo: '',
  welcomeText: '',
  footer: ''
})

const imageKeys = ref({
  logo: Date.now(),
  favicon: Date.now(),
  loginBackground: Date.now(),
  loginLogo: Date.now()
})

const showImages = ref({
  logo: true,
  favicon: true,
  loginBackground: true,
  loginLogo: true
})

const maintenanceLoading = ref(false)
const basicLoading = ref(false)

const mailForm = ref({
  mailerHost: '',
  mailerPort: '',
  mailerUser: '',
  mailerPass: '',
  mailerFrom: ''
})

const mailLoading = ref(false)
const testMailLoading = ref(false)

const smsForm = ref({
  provider: 'aliyun',
  // 阿里云配置
  accessKeyId: '',
  accessKeySecret: '',
  signName: '',
  templateCode: '',
  // 腾讯云配置
  secretId: '',
  secretKey: '',
  appId: '',
  signContent: '',
  // 华为云配置
  appKey: '',
  appSecret: '',
  channelNumber: '',
  signature: '',
  // 七牛云配置
  accessKey: '',
  secretKey: '',
  // 通用配置
  templateId: ''
})

const smsFormRef = ref()

// 维护配置相关方法
const handleMaintenanceSave = async () => {
  try {
    maintenanceLoading.value = true
    await updateMaintenanceConfig(maintenanceForm.value)
    ElMessage.success('保存成功')
  } catch (error) {
    ElMessage.error('保存失败')
  } finally {
    maintenanceLoading.value = false
  }
}

const fetchMaintenanceConfig = async () => {
  try {
    maintenanceLoading.value = true
    const res = await getMaintenanceConfig()
    if (res.code === 0 && res.data) {
      maintenanceForm.value = {
        enabled: res.data.enabled || false,
        message: res.data.message || ''
      }
    }
  } catch (error) {
    ElMessage.error('获取配置失败')
  } finally {
    maintenanceLoading.value = false
  }
}

// 基础信息配置相关方法
const handleBasicSave = async () => {
  try {
    // 验证系统名称长度
    if (basicForm.value.frontendName?.length > 8) {
      ElMessage.error('前台名称不能超过8个字符')
      return
    }
    if (basicForm.value.backendName?.length > 8) {
      ElMessage.error('后台名称不能超过8个字符')
      return
    }

    console.log('保存前的前台名称:', basicForm.value.frontendName)
    console.log('保存前的后台名称:', basicForm.value.backendName)
    basicLoading.value = true
    
    // 构建要保存的配置对象
    const configToSave = {
      ...basicForm.value,
      frontendName: basicForm.value.frontendName?.trim() || '证书查询系统',
      backendName: basicForm.value.backendName?.trim() || '证书管理系统'
    }
    
    const success = await systemStore.updateConfig(configToSave)
    if (success) {
      console.log('保存成功，更新后的前台名称:', configToSave.frontendName)
      console.log('保存成功，更新后的后台名称:', configToSave.backendName)
      // 重新获取系统配置
      await systemStore.fetchSystemConfig()
      console.log('重新获取配置后的前台名称:', systemStore.systemConfig.frontendName)
      console.log('重新获取配置后的后台名称:', systemStore.systemConfig.backendName)
      ElMessage.success('保存成功')
    } else {
      throw new Error('保存失败')
    }
  } catch (error) {
    console.error('保存出错:', error)
    ElMessage.error(error.message || '保存失败')
  } finally {
    basicLoading.value = false
  }
}

const fetchBasicConfig = async () => {
  try {
    basicLoading.value = true
    await systemStore.fetchSystemConfig()
    // 只在值为空时设置默认值
    basicForm.value = { 
      ...systemStore.systemConfig,
      frontendName: systemStore.systemConfig.frontendName || '证书查询系统',
      backendName: systemStore.systemConfig.backendName || '证书管理系统',
      welcomeText: systemStore.systemConfig.welcomeText || '欢迎使用证书管理系统，请登录您的账号',
      // 只在 footer 为 null 或 undefined 时设置默认值
      footer: systemStore.systemConfig.footer ?? '本系统为开源项目 <a href="https://gitee.com/yangfangqing/querysystem" target="_blank">@https://gitee.com/yangfangqing/querysystem</a>'
    }
  } catch (error) {
    ElMessage.error('获取配置失败')
  } finally {
    basicLoading.value = false
  }
}

const getImageUrl = (url) => {
  if (!url) return ''
  return `${url}?v=${Date.now()}`
}

// 文件上传相关方法
const handleUpload = async (file, field) => {
  try {
    // 检查文件大小
    const sizeLimit = {
      logo: 2 * 1024 * 1024, // 2MB
      favicon: 2 * 1024 * 1024, // 2MB
      loginBackground: 5 * 1024 * 1024, // 5MB
      loginLogo: 2 * 1024 * 1024 // 2MB
    }
    
    if (file.file.size > sizeLimit[field]) {
      const sizeMB = sizeLimit[field] / (1024 * 1024)
      ElMessage.error(`文件大小不能超过${sizeMB}MB`)
      return
    }

    // 检查文件类型
    const fileTypeMap = {
      'logo': { type: 'image/png', name: 'PNG图片' },
      'favicon': { type: 'image/x-icon', name: 'ICO图标' },
      'loginBackground': { type: 'image/jpeg', name: 'JPG图片' },
      'loginLogo': { type: 'image/png', name: 'PNG图片' }
    }
    
    const expectedType = fileTypeMap[field]
    if (expectedType && file.file.type !== expectedType.type) {
      ElMessage.error(`请上传${expectedType.name}格式的文件`)
      return
    }

    basicLoading.value = true
    const formData = new FormData()
    formData.append('file', file.file)
    formData.append('type', field)

    const response = await fetch('/api/upload/file', {
      method: 'POST',
      body: formData
    })
    
    if (!response.ok) {
      const errorData = await response.json()
      console.error('上传失败:', errorData)
      
      if (errorData.message) {
        throw new Error(errorData.message)
      }
      
      if (response.status === 413) {
        throw new Error('文件太大，请选择较小的文件')
      } else if (response.status === 415) {
        throw new Error('不支持的文件类型')
      } else if (response.status === 500) {
        throw new Error('服务器处理失败，请稍后重试')
      }
      
      const fieldTypeMap = {
        'logo': '系统Logo（PNG格式，小于2MB，120x40px）',
        'favicon': '浏览器图标（ICO格式，小于2MB，32x32px）',
        'loginBackground': '登录背景（JPG格式，小于5MB，1920x1080px）',
        'loginLogo': '登录标识（PNG格式，小于2MB，200x60px）'
      }
      throw new Error(`上传${fieldTypeMap[field]}失败，请检查文件是否符合要求`)
    }
    
    const result = await response.json()

    if (result.code === 0) {
      basicForm.value[field] = result.data.url
      
      // 静默保存更改到后端
      try {
        const configToSave = { ...basicForm.value }
        await systemStore.updateConfig(configToSave)
        ElMessage.success('上传成功')
      } catch (error) {
        console.error('保存配置失败:', error)
        ElMessage.warning('图片已上传，但保存配置失败')
      }
    } else {
      throw new Error(result.message || '上传失败，请检查文件格式是否正确')
    }
  } catch (error) {
    console.error('上传错误详情:', error)
    ElMessage({
      message: error.message,
      type: 'error',
      duration: 5000
    })
  } finally {
    basicLoading.value = false
  }
}

// 删除文件
const handleRemoveFile = async (field) => {
  // 先隐藏图片
  showImages.value[field] = false
  basicForm.value[field] = ''
  
  // 删除后自动保存
  try {
    basicLoading.value = true
    const configToSave = { ...basicForm.value }
    const success = await systemStore.updateConfig(configToSave)
    if (success) {
      await systemStore.fetchSystemConfig()
      ElMessage.success('删除成功')
    } else {
      throw new Error('保存失败')
    }
  } catch (error) {
    console.error('删除失败:', error)
    ElMessage.error(error.message || '删除失败')
  } finally {
    basicLoading.value = false
    // 延迟显示占位符
    setTimeout(() => {
      showImages.value[field] = true
    }, 100)
  }
}

// 获取邮件配置
const getMailSettings = async () => {
  mailLoading.value = true
  try {
    const res = await getMailConfig()
    if (res.code === 0 && res.data) {
      // 直接使用后端返回的数据，不设置默认值
      mailForm.value = res.data
    }
  } catch (error) {
    console.error('获取邮件配置失败:', error)
    ElMessage.error('获取配置失败')
  } finally {
    mailLoading.value = false
  }
}

// 保存邮件配置
const handleMailSave = async () => {
  // 表单验证
  if (!mailForm.value.mailerHost) {
    ElMessage.warning('请输入SMTP服务器地址')
    return
  }
  if (!mailForm.value.mailerPort) {
    ElMessage.warning('请输入SMTP端口')
    return
  }
  if (!mailForm.value.mailerUser) {
    ElMessage.warning('请输入邮箱账号')
    return
  }
  if (!mailForm.value.mailerPass) {
    ElMessage.warning('请输入邮箱密码')
    return
  }
  if (!mailForm.value.mailerFrom) {
    ElMessage.warning('请输入发件人信息')
    return
  }

  mailLoading.value = true
  try {
    const res = await updateMailConfig(mailForm.value)
    if (res.code === 0) {
      ElMessage.success('保存成功')
      // 重新获取最新配置
      await getMailSettings()
    }
  } catch (error) {
    console.error('保存邮件配置失败:', error)
    ElMessage.error('保存失败')
  } finally {
    mailLoading.value = false
  }
}

// 发送测试邮件
const handleTestMail = async () => {
  testMailLoading.value = true
  try {
    // 先保存配置
    const saveRes = await updateMailConfig(mailForm.value)
    if (saveRes.code === 0) {
      // 再发送测试邮件
      const res = await testMailSend()
      if (res.code === 0) {
        ElMessage.success('测试邮件发送成功')
      }
    }
  } finally {
    testMailLoading.value = false
  }
}

// 获取短信配置
const getSmsConfig = async () => {
  try {
    loading.value = true
    const res = await systemApi.getSmsConfig()
    if (res.code === 0 && res.data) {
      Object.assign(smsForm.value, res.data)
    }
  } catch (error) {
    console.error('获取短信配置失败:', error)
    ElMessage.error('获取配置失败')
  } finally {
    loading.value = false
  }
}

// 保存短信配置
const handleSaveSmsConfig = async () => {
  try {
    loading.value = true
    const res = await systemApi.updateSmsConfig(smsForm.value)
    if (res.code === 0) {
      ElMessage.success('保存成功')
      // 重新获取配置
      await getSmsConfig()
    }
  } catch (error) {
    console.error('保存短信配置失败:', error)
    ElMessage.error('保存失败')
  } finally {
    loading.value = false
  }
}

// 测试发送短信
const handleTestSms = async () => {
  try {
    loading.value = true
    await systemApi.testSmsSend()
    ElMessage.success('发送成功')
  } catch (error) {
    console.error('发送测试短信失败:', error)
    ElMessage.error('发送失败')
  } finally {
    loading.value = false
  }
}

// 存储表单数据
const storageForm = ref({
  type: 'local',
  provider: '',
  accessKey: '',
  secretKey: '',
  region: '',
  bucket: '',
  domain: '',          // 域名(必填)
  protocol: 'http'     // 协议(必填)
})

// 加载状态
const storageLoading = ref(false)
const testStorageLoading = ref(false)

// 存储方式变更处理
const handleStorageTypeChange = type => {
  if (type === 'local') {
    storageForm.value.provider = ''
    storageForm.value.accessKey = ''
    storageForm.value.secretKey = ''
    storageForm.value.region = ''
    storageForm.value.bucket = ''
    storageForm.value.domain = ''
  }
}

// 服务商变更处理
const handleStorageProviderChange = provider => {
  storageForm.value.accessKey = ''
  storageForm.value.secretKey = ''
  storageForm.value.region = ''
  storageForm.value.bucket = ''
  storageForm.value.domain = ''
}

// 动态标签
const accessKeyLabel = computed(() => {
  switch (storageForm.value.provider) {
    case 'aliyun':
      return 'AccessKey ID'
    case 'tencent':
      return 'SecretId'
    case 'qiniu':
      return 'AccessKey'
    case 'huawei':
      return 'AccessKey ID'
    default:
      return 'AccessKey'
  }
})

const secretLabel = computed(() => {
  switch (storageForm.value.provider) {
    case 'aliyun':
      return 'AccessKey Secret'
    case 'tencent':
      return 'SecretKey'
    case 'qiniu':
      return 'SecretKey'
    case 'huawei':
      return 'SecretKey'
    default:
      return 'AccessSecret'
  }
})

// 获取存储配置
const getStorageConfig = async () => {
  try {
    storageLoading.value = true
    const res = await systemApi.getStorageConfig()
    if (res.code === 0 && res.data) {
      Object.assign(storageForm.value, res.data)
    }
  } catch (error) {
    console.error('获取存储配置失败:', error)
    ElMessage.error('获取配置失败')
  } finally {
    storageLoading.value = false
  }
}

// 保存存储配置
const handleSaveStorage = async () => {
  if (storageForm.value.type === 'oss') {
    // 对象存储模式下的表单验证
    if (!storageForm.value.provider) {
      ElMessage.warning('请选择服务商')
      return
    }

    if (!storageForm.value.accessKey) {
      ElMessage.warning('请输入AccessKey')
      return
    }

    if (!storageForm.value.secretKey) {
      ElMessage.warning('请输入AccessSecret')
      return
    }

    if (!storageForm.value.region) {
      ElMessage.warning('请输入区域')
      return
    }

    if (!storageForm.value.bucket) {
      ElMessage.warning('请输入Bucket')
      return
    }

    if (!storageForm.value.domain) {
      ElMessage.warning('请输入域名')
      return
    }
  }

  try {
    storageLoading.value = true
    // 处理域名格式
    if (storageForm.value.domain) {
      storageForm.value.domain = storageForm.value.domain
        .replace(/^https?:\/\//, '')  // 去掉协议头
        .replace(/^(:\/\/|:|\/\/|\/)+/, '')  // 去掉开头的冒号和斜杠组合
        .replace(/\/+$/, '')          // 去掉结尾的斜杠
    }

    const res = await systemApi.updateStorageConfig(storageForm.value)
    if (res.code === 0) {
      ElMessage.success('保存成功')
      await getStorageConfig()
    }
  } catch (error) {
    console.error('保存存储配置失败:', error)
    ElMessage.error(error.message || '保存失败')
  } finally {
    storageLoading.value = false
  }
}

// 测试存储连接
const handleTestStorage = async () => {
  if (storageForm.value.type === 'local') {
    ElMessage.warning('本地存储无需测试连接')
    return
  }

  if (storageForm.value.type === 'oss') {
    // 对象存储模式下的表单验证
    if (!storageForm.value.provider) {
      ElMessage.warning('请选择服务商')
      return
    }

    if (!storageForm.value.accessKey) {
      ElMessage.warning('请输入AccessKey')
      return
    }

    if (!storageForm.value.secretKey) {
      ElMessage.warning('请输入AccessSecret')
      return
    }

    if (!storageForm.value.region) {
      ElMessage.warning('请输入区域')
      return
    }

    if (!storageForm.value.bucket) {
      ElMessage.warning('请输入Bucket')
      return
    }

    if (!storageForm.value.domain) {
      ElMessage.warning('请输入域名')
      return
    }
  }

  try {
    testStorageLoading.value = true
    await systemApi.testStorageConnection(storageForm.value)
    ElMessage.success('连接测试成功')
  } finally {
    testStorageLoading.value = false
  }
}

onMounted(() => {
  fetchMaintenanceConfig()
  fetchBasicConfig()
  getStorageConfig()
  getMailSettings()
  getSmsConfig()
})
</script>

<style scoped>
.admin-page-content {
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 50px;
  background-color: #F8FAFC;
  min-height: calc(100vh - 120px);
}

.settings-section {
  margin: 0;
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 4px;
  background-color: #F4F4F5;
}

.settings-section :deep(.el-card__header) {
  border-bottom: none;
  padding: 0;
  background-color: #fff;
}

.settings-section :deep(.el-card__body) {
  padding: 20px;
}

.maintenance-content {
  height: 80px;
  width: 100%;
  background-color: hwb(0 100% 0%);
  border-radius: 4px;
  padding: 24px;
}

.maintenance-form {
  display: flex;
  align-items: flex-start;
  gap: 16px;
}

.message-item {
  flex: 0.8;
  margin-bottom: 0;
}

.message-item :deep(.el-textarea__inner) {
  height: 32px;
  padding-top: 5px;
  padding-bottom: 5px;
}

.action-item {
  margin-bottom: 0;
  margin-left: 16px;
}

.settings-grid {
  display: grid;
  gap: 16px;
  grid-template-columns: repeat(auto-fit, minmax(360px, 1fr));
}

.settings-card {
  margin: 0;
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 4px;
  background-color: rgb(244, 244, 245);
  height: 100%;
  display: flex;
  flex-direction: column;
}

.settings-card :deep(.el-card__header) {
  border-bottom: 1px solid rgb(244, 244, 245);
  padding: 0;
  background-color: rgb(255, 255, 255);
}

.settings-card :deep(.el-card__body) {
  padding: 24px;
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: rgb(255, 255, 255);
}

.settings-card :deep(.el-form) {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 48px;
  padding: 0 20px;
  background-color: rgb(255, 255, 255);
  border-bottom: 1px solid rgb(244, 244, 245);
}

.card-header :deep(.el-button) {
  height: 32px;
  padding: 0 16px;
  font-size: 14px;
}

.card-title {
  position: relative;
  padding-left: 10px;
  font-size: 15px;
  font-weight: 500;
  color: var(--el-text-color-primary);
}

.card-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 3px;
  height: 16px;
  background-color: var(--el-color-primary);
  border-radius: 2px;
}

.upload-item {
  flex: 1;
  display: flex;
  flex-direction: row;
  gap: 24px;
}

.upload-wrapper {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.upload-label {
  font-size: 14px;
  color: var(--el-text-color-regular);
}

.upload-content {
  display: flex;
  gap: 24px;
}

.upload-area {
  width: 200px;
  height: 200px;
  border: 1px dashed var(--el-border-color);
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  background-color: var(--el-fill-color-blank);
  display: flex;
  align-items: center;
  justify-content: center;
}

.upload-area:hover {
  border-color: var(--el-color-primary);
}

.upload-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: var(--el-text-color-secondary);
  text-align: center;
  position: relative;
}

.upload-icon {
  font-size: 32px;
  color: var(--el-text-color-secondary);
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.upload-text {
  font-size: 16px;
  margin-bottom: 8px;
  line-height: 1;
}

.upload-tip {
  font-size: 13px;
  color: var(--el-text-color-secondary);
  line-height: 1.4;
  text-align: center;
  margin-top: 8px;
}

.upload-preview {
  position: relative;
  width: 200px;
  height: 200px;
  border: 1px solid var(--el-border-color);
  border-radius: 4px;
  overflow: hidden;
  background-color: var(--el-fill-color-blank);
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0;
  padding: 0;
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
  background: var(--el-fill-color-blank);
  display: block;
  margin: 0;
  padding: 0;
}

.preview-bg {
  object-fit: cover;
}

.preview-actions {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  background: rgba(0, 0, 0, 0.6);
  opacity: 0;
  transition: opacity 0.3s;
}

.preview-actions:hover {
  opacity: 1;
}

:deep(.el-input),
:deep(.el-textarea) {
  max-width: 100%;
}

:deep(.el-switch) {
  margin-right: 8px;
}

:deep(.el-form-item) {
  margin-bottom: 24px;
}

:deep(.el-form-item:last-child) {
  margin-bottom: 0;
}

.maintenance-form :deep(.el-button--primary) {
  --el-button-text-color: #fff !important;
  --el-button-bg-color: var(--el-color-primary) !important;
  --el-button-border-color: var(--el-color-primary) !important;
  --el-button-hover-text-color: #fff !important;
  --el-button-hover-bg-color: var(--el-color-primary) !important;
  --el-button-hover-border-color: var(--el-color-primary) !important;
  --el-button-active-text-color: #fff !important;
  color: #fff !important;
  background-color: var(--el-color-primary) !important;
  border-color: var(--el-color-primary) !important;
  height: 32px !important;
  padding: 0 16px !important;
  font-size: 14px !important;
}

.el-button.el-button--primary {
  background-color: var(--el-color-primary) !important;
  border-color: var(--el-color-primary) !important;
  color: #fff !important;
  height: 32px !important;
  padding: 0 16px !important;
  font-size: 14px !important;
}

.admin-page :deep(.el-button--primary) {
  --el-button-bg-color: var(--el-color-primary) !important;
  --el-button-border-color: var(--el-color-primary) !important;
  --el-button-text-color: #fff !important;
  --el-button-hover-bg-color: var(--el-color-primary) !important;
  --el-button-hover-border-color: var(--el-color-primary) !important;
  --el-button-hover-text-color: #fff !important;
  --el-button-active-text-color: #fff !important;
  background-color: var(--el-color-primary) !important;
  border-color: var(--el-color-primary) !important;
  color: #fff !important;
  height: 32px !important;
  padding: 0 16px !important;
  font-size: 14px !important;
}

.card-header :deep(.el-button--primary) {
  background-color: var(--el-color-primary) !important;
  border-color: var(--el-color-primary) !important;
  color: #fff !important;
  height: 32px !important;
  padding: 0 16px !important;
  font-size: 14px !important;
}

.settings-card :deep(.el-button--primary),
.maintenance-form :deep(.el-button--primary) {
  --el-button-text-color: #fff !important;
  --el-button-bg-color: var(--el-color-primary) !important;
  --el-button-border-color: var(--el-color-primary) !important;
  --el-button-hover-text-color: #fff !important;
  --el-button-hover-bg-color: var(--el-color-primary) !important;
  --el-button-hover-border-color: var(--el-color-primary) !important;
  --el-button-active-text-color: #fff !important;
  color: #fff !important;
  background-color: var(--el-color-primary) !important;
  border-color: var(--el-color-primary) !important;
  height: 32px !important;
  padding: 0 16px !important;
  font-size: 14px !important;
}

.mail-content {
  width: 100%;
  background-color: #fff;
  border-radius: 4px;
  padding: 24px;
}

.mail-form {
  min-height: 32px;
  width: 100%;
  display: flex;
  align-items: flex-start;
  gap: 16px;
  flex-wrap: wrap;

  :deep(.el-form-item) {
    margin-bottom: 0;
    flex: 1;
    min-width: 200px;
  }

  :deep(.el-form-item:nth-child(2)) {
    flex: 0.5;
    min-width: 120px;
  }

  :deep(.el-input) {
    width: 100%;
  }
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.header-actions :deep(.el-button) {
  margin-left: 0;
}

.sms-content {
  background-color: #fff;
  border-radius: 4px;
  min-height: 80px;
  display: flex;
  align-items: flex-start;
  padding: 20px;
}
.sms-form {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 16px;
}
.provider-row {
  width: 100%;
  display: flex;
  align-items: center;
}
.provider-row :deep(.el-form-item) {
  margin-bottom: 0;
}
.provider-row :deep(.el-select) {
  width: 100px;
}
.config-row {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
}
.config-row :deep(.el-form-item) {
  margin-bottom: 0;
  margin-right: 8px;
}
.config-row :deep(.el-input) {
  width: 180px;
}
.storage-content {
  background-color: #fff;
  border-radius: 4px;
  padding: 24px;
}

.storage-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin-bottom: 16px;
}

.storage-form:last-child {
  margin-bottom: 0;
}

.storage-form :deep(.el-form-item) {
  margin-bottom: 0;
}

.storage-form :deep(.el-select),
.storage-form :deep(.el-input) {
  width: 100%;
}

.storage-form :deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px var(--el-border-color) inset;
}

.storage-form :deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px var(--el-border-color-hover) inset;
}

.storage-form :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px var(--el-color-primary) inset;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: -8px;
}

.card-title {
  font-size: 16px;
  font-weight: 500;
  color: var(--el-text-color-primary);
}

.header-actions {
  display: flex;
  gap: 8px;
}

.settings-section {
  margin-bottom: 16px;
}

.settings-section:last-child {
  margin-bottom: 0;
}

:deep(.el-card__header) {
  padding: 16px 20px;
  border-bottom: 1px solid var(--el-border-color-light);
}

:deep(.el-card__body) {
  padding: 0;
}

.domain-wrapper {
  display: flex;
  align-items: center;
  gap: 0;
}

.domain-wrapper :deep(.el-select) {
  margin-right: -1px;
}

.domain-wrapper :deep(.el-select .el-input__wrapper) {
  border-top-right-radius: 0;
  border-bottom-right-radius: 0;
}

.domain-wrapper :deep(.el-input .el-input__wrapper) {
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
}

.storage-row {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin-bottom: 16px;
}

.storage-row:last-child {
  margin-bottom: 0;
}

.storage-row :deep(.el-form-item) {
  margin-bottom: 0;
  display: flex;
  align-items: center;
}

.storage-row :deep(.el-form-item__content) {
  margin-left: 0 !important;
}

@media screen and (max-width: 768px) {
  .storage-row {
    flex-direction: column;
    gap: 12px;
  }
  
  .storage-row :deep(.el-form-item) {
    width: 100%;
  }
  
  .storage-row :deep(.el-select),
  .storage-row :deep(.el-input),
  .domain-wrapper {
    width: 100% !important;
  }
  
  .domain-wrapper :deep(.el-select) {
    width: 100px !important;
  }
  
  .domain-wrapper :deep(.el-input) {
    flex: 1;
  }
}
</style> 